package a;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JTextField captchaField;
    private JButton loginButton;
    private JLabel captchaLabel;
    private String captcha;

    public LoginFrame() {
        super("登录");

        // 创建用户名和密码输入框以及验证码标签和输入框
        JPanel panel = new JPanel(new GridLayout(3, 2));
        panel.add(new JLabel("用户名:"));
        usernameField = new JTextField();
        panel.add(usernameField);
        panel.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        panel.add(passwordField);
        panel.add(new JLabel("验证码:"));
        captchaField = new JTextField();
        panel.add(captchaField);

        // 创建登录按钮
        loginButton = new JButton("登录");
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());
                String inputCaptcha = captchaField.getText();
                if (inputCaptcha.equals(captcha)) {
                    // 在这里编写登录验证的代码
                    System.out.println("用户名：" + username + " 密码：" + password);
                    JOptionPane.showMessageDialog(null, "登录或注册成功！");
                } else {
                    JOptionPane.showMessageDialog(null, "验证码错误！");
                }
            }
        });

        // 创建验证码标签
        captchaLabel = new JLabel();
        updateCaptcha();
        captchaLabel.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                updateCaptcha();
            }
        });

        // 添加组件到窗口
        add(panel, BorderLayout.CENTER);
        add(loginButton, BorderLayout.SOUTH);
        add(captchaLabel, BorderLayout.EAST);

        // 设置窗口大小和默认关闭操作
        setSize(400, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    // 更新验证码
    private void updateCaptcha() {
        captcha = generateCaptcha();
        captchaLabel.setText(captcha);
    }

    // 生成随机验证码
    private String generateCaptcha() {
        Random rand = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int c = rand.nextInt(26) + 'a';
            sb.append((char)c);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        new LoginFrame();
    }
}
